package org.c41.graphics.swing;

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class JC41TextField extends JTextField {

	public JC41TextField(){
		super();
		setDocument(new C41Document());
	}
	
	public JC41TextField(TextFieldRestrictor d){
		this();
		setRestrictor(d);
	}
	
	public void setRestrictor(TextFieldRestrictor r){
		((C41Document)getDocument()).inner_setRestrictor(r);
	}
	
}

class C41Document extends PlainDocument{
	
	private TextFieldRestrictor r;
	
	void inner_setRestrictor(TextFieldRestrictor d){
		this.r=d;
	}
	
	@Override
	public void insertString(int offset, String text, AttributeSet pp) throws BadLocationException {
		for(int i=0;i<text.length();i++){
			char ch = text.charAt(i);
			if(r==null||r.access(ch, i+offset)){
				super.insertString(i+offset, String.valueOf(ch), pp);
			}
		}
	}
	
}